<template>
  <div class="notice-management-container">
    <!-- 搜索栏 -->
    <el-row class="search-row">
      <el-col :span="8">
        <el-input
          v-model="searchParams.title" 
          placeholder="请输入公告标题" 
          style="width: 100%;"
        ></el-input>
      </el-col>
      <el-col :span="8">
        <el-button
          type="danger"
          size="large"
          @click="loadNoticeList"
          style="margin-right: 10px;"
        >
          <i class="el-icon-search"></i> 搜索
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="showAddDialog"
        >
          <i class="el-icon-circle-plus"></i> 添加公告
        </el-button>
      </el-col>
    </el-row>

    <!-- 添加公告对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="添加公告"
      width="450px"
    >
      <el-form ref="addForm" :model="addForm" label-width="100px">
        <el-form-item label="公告标题" :rules="{ required: true, message: '请输入公告标题', trigger: 'blur' }">
          <el-input v-model="addForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" :rules="{ required: true, message: '请输入公告内容', trigger: 'blur' }">
          <el-input 
            v-model="addForm.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布人" :rules="{ required: true, message: '请输入发布人', trigger: 'blur' }">
          <el-input v-model="addForm.publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公告状态" :rules="{ required: true, message: '请选择公告状态', trigger: 'change' }">
          <el-radio-group v-model="addForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addNotice">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑公告对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑公告"
      width="450px"
    >
      <el-form ref="editForm" :model="editForm" label-width="100px">
        <el-form-item label="公告ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="公告标题" :rules="{ required: true, message: '请输入公告标题', trigger: 'blur' }">
          <el-input v-model="editForm.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公告内容" :rules="{ required: true, message: '请输入公告内容', trigger: 'blur' }">
          <el-input 
            v-model="editForm.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布人" :rules="{ required: true, message: '请输入发布人', trigger: 'blur' }">
          <el-input v-model="editForm.publisher" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="公告状态" :rules="{ required: true, message: '请选择公告状态', trigger: 'change' }">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="editForm.createTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="editForm.updateTime" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateNotice">确定</el-button>
      </template>
    </el-dialog>

    <!-- 状态容器 -->
    <div class="state-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-mask">
        <el-loading-spinner size="large"></el-loading-spinner>
        <p>正在加载数据，请稍候...</p>
      </div>

      <!-- 空数据提示 -->
      <div v-else-if="noticeList.length === 0" class="empty-data">
        <i class="el-icon-data-empty"></i>
        <p>暂无公告数据</p>
        <el-button type="primary" @click="loadNoticeList">刷新</el-button>
      </div>

      <!-- 公告列表 -->
      <el-table
        v-else
        :data="noticeList"
        stripe
        highlight-current-row
        border
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column
          prop="id"
          label="公告ID"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="title"
          label="公告标题"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="content"
          label="公告内容"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-tooltip effect="dark" :content="scope.row.content" placement="top">
              <div class="cell-content">{{ scope.row.content.length > 50 ? scope.row.content.substring(0, 50) + '...' : scope.row.content }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="publisher"
          label="发布人"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="公告状态"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          label="操作"
          width="200"
          align="center"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="showEditDialog(scope.row)"
              style="margin-right: 5px;"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteNotice(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.page"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="pagination.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px;"
    ></el-pagination>
  </div>
</template>

<script>
import axios from 'axios'
import { useUserInfoStore } from "../pinia/userinfo"

export default {
  data() {
    return {
      noticeList: [], 
      searchParams: {
        title: '', 
        page: 1,
        limit: 10
      },
      sprheaders: {
        uname: "",
        token: ""
      },
      addDialogVisible: false, 
      editDialogVisible: false, 
      addForm: {
        title: '',
        content: '',
        publisher: '',
        status: 1
      }, 
      editForm: {
        id: '',
        title: '',
        content: '',
        publisher: '',
        status: 1,
        createTime: '',
        updateTime: ''
      }, 
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      loading: false
    }
  },
  created() {
    const userStore = useUserInfoStore();
    this.sprheaders.uname = userStore.getUsername
    this.sprheaders.token = userStore.getToken
    this.loadNoticeList()
  },
  methods: {
    // 加载公告列表
    loadNoticeList() {
      this.loading = true;
      
      const params = {
        title: this.searchParams.title, 
        page: this.pagination.page,
        limit: this.pagination.limit
      };

      axios.get(this.$baseUrl.SPRURL + "v2/notices/getnoticelist", {
        headers: this.sprheaders,
        params: params
      })
      .then(res => {
        if (res.data.code === 0) {
          this.noticeList = res.data.data || [];
          // 获取公告总数
          this.getNoticeCount();
        } else {
          this.$message.error(res.data.msg || '数据加载失败');
        }
      })
      .catch(error => {
        console.error('API请求错误:', error);
        this.$message.error('网络请求失败，请重试');
      })
      .finally(() => {
        this.loading = false;
      });
    },

    // 获取公告总数
    getNoticeCount() {
      axios.get(this.$baseUrl.SPRURL + "v2/notices/getnoticecount", {
        headers: this.sprheaders
      })
      .then(res => {
        if (res.data.code === 0) {
          this.pagination.total = res.data.data || 0;
        } else {
          console.error('获取公告总数失败:', res.data.msg);
        }
      })
      .catch(error => {
        console.error('获取公告总数错误:', error);
      });
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.limit = val;
      this.pagination.page = 1;
      this.loadNoticeList();
    },

    // 分页页码变化
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.loadNoticeList();
    },

    // 显示添加对话框
    showAddDialog() {
      this.addDialogVisible = true;
      this.addForm = { 
        title: '',
        content: '',
        publisher: '',
        status: 1
      };
    },

    // 显示编辑对话框
    showEditDialog(row) {
      this.editDialogVisible = true;
      this.editForm = { 
        id: row.id,
        title: row.title,
        content: row.content,
        publisher: row.publisher,
        status: row.status,
        createTime: row.createTime,
        updateTime: row.updateTime
      };
    },

    // 添加公告
    addNotice() {
      // 验证表单
      this.$refs.addForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        axios.post(this.$baseUrl.SPRURL + "v2/notices/notices", this.addForm, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('公告添加成功');
            this.addDialogVisible = false;
            this.loadNoticeList();
          } else {
            this.$message.error(res.data.msg || '公告添加失败');
          }
        })
        .catch(error => {
          console.error('添加公告错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 更新公告
    updateNotice() {
      // 验证表单
      this.$refs.editForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写所有必填字段');
          return;
        }

        axios.put(this.$baseUrl.SPRURL + "v2/notices/notices", this.editForm, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('公告更新成功');
            this.editDialogVisible = false;
            this.loadNoticeList();
          } else {
            this.$message.error(res.data.msg || '公告更新失败');
          }
        })
        .catch(error => {
          console.error('更新公告错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      });
    },

    // 删除公告
    deleteNotice(row) {
      this.$confirm('确认删除该公告吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        axios.delete(this.$baseUrl.SPRURL + `v2/notices/notices/${row.id}`, {
          headers: this.sprheaders
        })
        .then(res => {
          if (res.data.code === 0) {
            this.$message.success('公告删除成功');
            this.loadNoticeList();
          } else {
            this.$message.error(res.data.msg || '公告删除失败');
          }
        })
        .catch(error => {
          console.error('删除公告错误:', error);
          this.$message.error('网络请求失败，请重试');
        });
      })
      .catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<style scoped>
.notice-management-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 400px;
  position: relative;
}

.search-row {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
}

.el-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-pagination {
  margin-top: 30px;
  text-align: right;
}

/* 状态容器样式 */
.state-container {
  min-height: 300px;
  position: relative;
}

/* 加载状态样式 */
.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

/* 空数据提示样式 */
.empty-data {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  color: #909399;
}

.empty-data i {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-data p {
  margin-bottom: 20px;
  font-size: 16px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-row el-col {
    span: 24;
  }
  .el-table el-table-column {
    min-width: auto;
  }
}

/* 表格内容样式 */
.cell-content {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>